using UnityEngine;
using System.Collections;

/// \class  gkAbyssalGiantSubmarineBoostController
/// \brief  The submarine boost controller
[AddComponentMenu("GK/AbyssalGiant/Submarine/gkAbyssalGiantSubmarineBoostController")]
public class gkAbyssalGiantSubmarineBoostController : MonoBehaviour 
{
	/// The power consumption rate
	public float PowerConsumtionRate = 0.2f;
	
	/// The input
	private gkAbyssalGiantSubmarineInput m_rSubmarineInput;
	
	/// Boosting
	private bool m_bBoosting;
	
	/// Is the owner shocked?
	private bool m_bShocked;
	
	///The scrolling info
	private gkScrollingInfo m_rScrollingInfo;
	
	/// The power component
	private gkPowerComponent m_rPowerComponent;
	
	/// \brief  Called just after the game begin to play
	void Start()
	{
		// Grab the scrolling info
		m_rScrollingInfo = GameObject.Find("ScrollingInfo").GetComponent<gkScrollingInfo>();
		
		// Grab the input
        m_rSubmarineInput = GetComponent<gkAbyssalGiantSubmarineInput>();
		
		// Get the power component
		m_rPowerComponent = GetComponent<gkPowerComponent>();
	}
	
	/// \brief  Called when the component is enabled
	void OnEnable() 
	{
		// Listen the shock event of the owner
		GetComponent<gkEventComponent>().AddEventHandler(gkAbyssalGiantShockEvent.ShockBegin, HandleShockBeginEvent);
		GetComponent<gkEventComponent>().AddEventHandler(gkAbyssalGiantShockEvent.ShockEnd, HandleShockEndEvent);
	}
	
	/// \brief  Called when the component is disabled
	void OnDisable() 
	{	
		// Remove the shock event of the owner
		GetComponent<gkEventComponent>().RemoveEventHandler(gkAbyssalGiantShockEvent.ShockBegin, HandleShockBeginEvent);
		GetComponent<gkEventComponent>().RemoveEventHandler(gkAbyssalGiantShockEvent.ShockEnd, HandleShockEndEvent);
	}
	
	/// \brief  Event called each frame within the player controller
	void Update()
	{
		if(m_bShocked == false)
		{
			if(m_rSubmarineInput.IsBoost() && (m_rPowerComponent.GetPower() > 0.0f))
			{
				SetBoosting(true);
				m_rPowerComponent.UsePower(PowerConsumtionRate * Time.deltaTime);
			}
			else
			{
				SetBoosting(false);
			}
		}
	}
	
	/// Handle the owner collision event
	void HandleShockBeginEvent(Object a_rEvent)
	{
		SetShocked(true);
	}
	
	/// Handle the owner collision event
	void HandleShockEndEvent(Object a_rEvent)
	{
		SetShocked(false);
	}
	
	/// Set if the submarine is boosting or not
	void SetShocked(bool a_bShocked)
	{
		if(m_bShocked != a_bShocked)
		{
			m_bShocked = a_bShocked;
			if(m_bShocked)
			{
				SetBoosting(false);
			}
		}
	}
	
	/// \brief Set boosting
	void SetBoosting(bool a_bBoosting)
	{
		if(m_bBoosting != a_bBoosting)
		{
			m_bBoosting = a_bBoosting;
			if(m_bBoosting)
			{
				// Boost the scrolling
				m_rScrollingInfo.Boost(1.0f, -1.0f, 0.25f);
			}
			else
			{
				// Stop the boost
				m_rScrollingInfo.StopBoost(0.25f);
			}
		}
	}
}